#include <iostream>
#include <vector>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/wait.h>
#include "Task.hpp"
using namespace std;
const int num=5;
static int number=1;


class channel
{
public:
    channel(int fd,pid_t id):ctrlfd(fd),workerid(id)
    {
        name="channel-"+to_string(number++);
    }
public:
    int ctrlfd;
    pid_t workerid;
    std::string name;
};

void work()
{
    while(true)
    {
        int code =0;
        ssize_t n=read(0,&code,sizeof(code));
        if(n==sizeof(code))
        {
            init.runtask();//这里我没有选择任务
        }
        else if(n==0)
        {
            cout<<"quit"<<endl;
            break;
        }
    }
}
void Printfd(vector<int> v)
{
    for(auto i:v)
    {
        cout<<i<<' ';
    }
    cout<<endl;
}
void CreateChannels(vector<channel>* c)
{
    vector<int> old;
    for(int i=0;i<num;i++)
    {
        int pipefd[2];
        int n=pipe(pipefd);
        assert(n==0);

        pid_t id=fork();
        assert(id!=-1);
        if(id==0)
        {
            //子
            if(!old.empty())
            {
                for(auto fd:old)
                {
                    close(fd);
                }
                //Printfd(old);
            }
            close(pipefd[1]);//关闭写端，相当于只读
            dup2(pipefd[0],0);
            work();
            exit(0);
        }
        //父
        close(pipefd[0]);
        c->push_back(channel(pipefd[1],id));//进程pid
        old.push_back(pipefd[1]);
    }
}
void SendCommand(const vector<channel> &c,int num=-1)
{
    int pos=0;
    while(true)
    {
        //选择信道
        const auto &channel=c[pos++];
        pos%=c.size();
        cout<<channel.name<<"worker is"<<channel.workerid<<endl;
        write(channel.ctrlfd,0,sizeof(0));//这里随便写其实都行
        if(num>0)
        {
            num--;
        }
        else
        {
            break;//运行次数
        }
        sleep(1);//不那么快完成任务
    }
}
void ReleaseChannels(vector<channel> cs)
{
    //关闭打开的文件描述符，回收子进程
    for(auto channel:cs)
    {
        close(channel.ctrlfd);
        waitpid(channel.workerid,nullptr,0);
    }
}
int main()
{
    vector<channel> channels;
    CreateChannels(&channels);
    SendCommand(channels,10);
    ReleaseChannels(channels);

    return 0;
}